package CanvaWeb.CanvaWeb.Service;

import CanvaWeb.CanvaWeb.Repository.RoomMemberRepository;
import CanvaWeb.CanvaWeb.Repository.RoomRepository;
import CanvaWeb.CanvaWeb.pojo.Room;
import CanvaWeb.CanvaWeb.pojo.RoomMember;
import CanvaWeb.CanvaWeb.pojo.RoomStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RoomService {

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private RoomMemberRepository roomMemberRepository;

    /**
     * 匹配房间
     * @param userId 用户ID
     * @return 匹配到的房间
     */
    public Room matchRoom(Long userId) {
        // 找到一个状态为 WAITING 且未满的房间
        List<Room> rooms = roomRepository.findAvailableRooms("WAITING");
        if (!rooms.isEmpty()) {
            Room room = rooms.get(0); // 获取第一个符合条件的房间
            joinRoom(room.getId(), userId); // 用户加入房间
            return room;
        }

        // 如果没有合适房间，则创建一个新房间
        Room newRoom = createRoom("房间_" + System.currentTimeMillis(), 10); // 默认容量为 10
        joinRoom(newRoom.getId(), userId);
        return newRoom;
    }

    /**
     * 创建房间
     * @param name 房间名称
     * @param capacity 房间最大容量
     * @return 创建的房间
     */
    public Room createRoom(String name, Integer capacity) {
        Room room = new Room();
        room.setName(name);
        room.setCapacity(capacity);
        room.setCurrentPlayers(0);  // 初始化当前玩家为 0
        room.setStatus(RoomStatus.WAITING);  // 设置房间状态为 "WAITING"
        return roomRepository.save(room);  // 保存房间
    }



    /**
     * 用户加入房间
     * @param roomId 房间ID
     * @param userId 用户ID
     */
    public void joinRoom(Long roomId, Long userId) {
        // 检查房间是否存在
        Room room = roomRepository.findById(roomId)
                .orElseThrow(() -> new RuntimeException("房间不存在"));

        // 检查房间是否已满
        if (room.getCurrentPlayers() >= room.getCapacity()) {
            throw new RuntimeException("房间已满");
        }

        // 更新房间当前玩家数
        room.setCurrentPlayers(room.getCurrentPlayers() + 1);
        roomRepository.save(room);

        // 添加用户到房间成员表
        RoomMember member = new RoomMember();
        member.setRoomId(roomId);
        member.setUserId(userId);
        roomMemberRepository.save(member);
    }

    /**
     * 获取所有房间列表
     * @return 房间列表
     */
    public List<Room> getRoomList() {
        return roomRepository.findAll(); // 获取所有房间
    }

    public void changeUserRole(Long roomId, Long userId, String newRole) {
        // 获取房间
        Room room = roomRepository.findById(roomId)
                .orElseThrow(() -> new RuntimeException("房间未找到"));

        // 获取房间成员
        RoomMember roomMember = roomMemberRepository.findByRoomIdAndUserId(roomId, userId)
                .orElseThrow(() -> new RuntimeException("用户不在该房间"));

        // 如果当前角色已经是新角色，不需要修改
        if (roomMember.getRole().equals(newRole)) {
            throw new RuntimeException("用户已经拥有该角色");
        }

        // 更新用户角色
        roomMember.setRole(newRole);
        roomMemberRepository.save(roomMember);
    }


    public String getUserRole(Long roomId, Long userId ) {
        System.out.println("查询房间: " + roomId + " 中的用户: " + userId);

        RoomMember roomMember = roomMemberRepository.findByRoomIdAndUserId(roomId, userId)
                .orElseThrow(() -> new RuntimeException("用户未在该房间中"));

        // 找到用户角色并返回
        System.out.println("找到用户角色: " + roomMember.getRole());
        return roomMember.getRole();
    }
    public Room getRoomById(Long roomId) {
        // 根据房间ID从数据库中查询房间信息
        return roomRepository.findById(roomId).orElse(null);
    }

    // 根据房间名搜索房间
    public List<Room> searchRoomsByName(String name) {
        return roomRepository.findByNameContainingIgnoreCase(name);
    }

    public void startGame(Long roomId) {
        Room room = getRoomById(roomId);
        if (room != null) {
            room.setStatus(RoomStatus.IN_PROGRESS);  // 更新房间状态为进行中
            roomRepository.save(room);  // 保存更新的房间状态
        }
    }

    public Room getRoom(Long roomId) {
        return roomRepository.findById(roomId)
                .orElseThrow(() -> new RuntimeException("房间未找到"));
    }
}
